#include <iostream>
#include <sstream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include "server.h"

enum def_conf_type { RED, GREEN, BLUE };

struct address_info {
	std::string name = "";
	std::string address = "";
};

typedef struct tag_config_info
{
	std::string outbound_ip = "";
	std::string outbound_name = "";
	std::string inbound_ip = "";
	std::string inbound_name = "";
	address_info addr_info;
	def_conf_type conf_type = def_conf_type::GREEN;
	int listen_port = 0;
	int tx_port = 0;
} config_info;

std::ostream& operator<<(std::ostream& os, const def_conf_type& c) {
	switch (c) {
	case def_conf_type::RED: os << "RED"; break;
	case def_conf_type::GREEN: os << "GREEN"; break;
	case def_conf_type::BLUE: os << "BLUE"; break;
	}
	return os;
}

std::istream& operator>>(std::istream& is, def_conf_type& c) {
	std::string str;
	is >> str;
	if (str == "RED") {
		c = def_conf_type::RED;
	}
	else if (str == "GREEN") {
		c = def_conf_type::GREEN;
	}
	else if (str == "BLUE") {
		c = def_conf_type::BLUE;
	}
	else {
		is.setstate(std::ios::failbit);
	}
	return is;
}

int server()
{
	// 创建一个TCP监听套接字
	int listen_sock = socket(AF_INET, SOCK_STREAM, 0);
	struct sockaddr_in server_addr;
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(12345); // 监听这个端口
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	bind(listen_sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
	listen(listen_sock, 5);

	std::cout << "Listening on port 12345..." << std::endl;

	// 等待连接
	int conn_sock = accept(listen_sock, NULL, NULL);

	std::cout << "Received connection from sender..." << std::endl;

	// 接收数据
	char buffer[1024];
	int n = recv(conn_sock, buffer, sizeof(buffer), 0);

	// 将接收到的数据解析为配置信息
	std::stringstream ss(buffer);
	config_info config;
	ss >> config.outbound_ip;
	ss >> config.outbound_name;
	ss >> config.inbound_ip;
	ss >> config.inbound_name;
	ss >> config.addr_info.name;
	ss >> config.addr_info.address;
	ss >> config.conf_type;
	ss >> config.listen_port;
	ss >> config.tx_port;

	// 输出配置信息
	std::cout << "Configuration:" << std::endl;
	std::cout << "outbound_ip: " << config.outbound_ip << std::endl;
	std::cout << "outbound_name: " << config.outbound_name << std::endl;
	std::cout << "inbound_ip: " << config.inbound_ip << std::endl;
	std::cout << "inbound_name: " << config.inbound_name << std::endl;
	std::cout << "addr_info.name: " << config.addr_info.name << std::endl;
	std::cout << "addr_info.address: " << config.addr_info.address << std::endl;
	std::cout << "conf_type: " << static_cast<int>(config.conf_type) << std::endl;
	std::cout << "listen_port: " << config.listen_port << std::endl;
	std::cout << "tx_port: " << config.tx_port << std::endl;

	// 关闭连接
	close(conn_sock);
	close(listen_sock);

	return 0;
}
